import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AccountDetail from './components/AccountDetail';
import AddFrom from './components/AddForm';
import type { AddItem, TableListItem } from './data';
import { addAdmin, queryAdminDetail, queryAdminList, removeAdmin, resetAdmin } from './service';
import { SUCCESS_CODE } from '@/utils/request';

const TableList: React.FC = () => {
  const [sorter, setSorter] = useState<string>('');
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<string>('');
  const actionRef = useRef<ActionType>();

  const handleAdd = async (fields: AddItem) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addAdmin(fields);
      if (res.code === SUCCESS_CODE) {
        message.success('添加成功');
        handleAddModalVisible(false);
        actionRef.current?.reload();
        return true;
      } else {
        message.error(res.message || '添加失败');
      }
    } catch (error) {
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
      return false;
    } finally {
      hide();
    }
    return false;
  };

  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await removeAdmin(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const handleReset = async (fields: { id: string }) => {
    const hide = message.loading('正在重置');
    try {
      await resetAdmin(fields);
      hide();
      message.success('重置成功');
      return true;
    } catch (error) {
      hide();
      message.error('重置失败请重试！');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '管理员名称',
      dataIndex: 'name',
    },
    {
      title: '管理员账号',
      dataIndex: 'userName',
    },
    {
      title: '角色',
      dataIndex: 'roles',
      hideInSearch: true,
      render: (_, record) => (
        <div>
          {record.roles?.map((item) => (
            <div key={item.id}>{item.name}</div>
          ))}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setClickItemId(record.id);
        };

        const onResetPassword = () => {
          const { id, userName } = record;
          Modal.confirm({
            title: '重置密码',
            content: (
              <>
                <Divider />
                <p>确认要重置用户 </p>
                <span style={{ fontWeight: 'bolder' }}>{userName}</span>
                <p> 的密码?</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleReset({ id });
            },
          });
        };

        const onClickRemove = () => {
          const { id, userName } = record;
          Modal.confirm({
            title: `删除管理员 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除管理员</p>
                <span style={{ fontWeight: 'bolder' }}>{userName}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
          });
        };

        return (
          <div>
            <a onClick={onClickDetail}>详情</a>
            <Divider type="vertical" />
            <a onClick={onResetPassword}>重置密码</a>
            <Divider type="vertical" />
            <a onClick={onClickRemove}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="管理员列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleAddModalVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        rowSelection={false}
        request={(params = {}) => {
          return queryAdminList(params);
        }}
        columns={columns}
      />
      <AddFrom
        modalVisible={addModalVisible}
        onSubmit={(value: AddItem) => handleAdd(value)}
        onCancel={() => handleAddModalVisible(false)}
      />
      <Drawer
        visible={!!clickItemId && detailVisible}
        onClose={() => setDetailVisible(false)}
        width="30%"
      >
        {!!clickItemId && detailVisible && (
          <AccountDetail id={clickItemId} request={(id) => queryAdminDetail({ id })} />
        )}
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
